package com.newshub.admin.service.impl;

import com.newshub.common.fetch.FetchResult;
import com.newshub.common.fetch.FetchTask;
import com.newshub.admin.service.AsyncFetchService;
import com.newshub.logging.annotation.BusinessLog;
import com.newshub.logging.annotation.LogLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 异步抓取服务实现
 */
@Slf4j
@Service
public class AsyncFetchServiceImpl implements AsyncFetchService {
    
    @Autowired
    private FetchTask rssFetchTask;
    
    // 存储任务结果的内存缓存（生产环境建议使用Redis）
    private final Map<String, FetchResult> taskResults = new ConcurrentHashMap<>();
    
    @Override
    @BusinessLog(module = "异步抓取管理", description = "提交异步抓取任务", level = LogLevel.INFO)
    public String executeFetchAsync(Long feedId) {
        String taskId = generateTaskId();
        
        // 立即返回任务ID，让用户知道任务已提交
        log.info("提交异步抓取任务，taskId: {}, feedId: {}", taskId, feedId);
        
        // 异步执行抓取任务
        executeFetchTaskAsync(taskId, feedId);
        
        return taskId;
    }
    
    @Override
    @BusinessLog(module = "异步抓取管理", description = "查询抓取任务结果", level = LogLevel.INFO)
    public FetchResult getFetchResult(String taskId) {
        FetchResult result = taskResults.get(taskId);
        if (result == null) {
            // 任务不存在或还在执行中
            return FetchResult.builder()
                    .success(false)
                    .errorMessage("任务不存在或还在执行中")
                    .build();
        }
        return result;
    }
    
    /**
     * 异步执行抓取任务
     */
    @Async("fetchTaskExecutor")
    @BusinessLog(module = "异步抓取管理", description = "执行异步抓取任务", level = LogLevel.INFO)
    public void executeFetchTaskAsync(String taskId, Long feedId) {
        try {
            log.info("开始执行异步抓取任务，taskId: {}, feedId: {}", taskId, feedId);
            
            // 执行抓取任务
            FetchResult result = rssFetchTask.execute(feedId);
            
            // 存储结果
            taskResults.put(taskId, result);
            
            log.info("异步抓取任务完成，taskId: {}, success: {}, newsCount: {}", 
                    taskId, result.isSuccess(), result.getNewsCount());
            
        } catch (Exception e) {
            log.error("异步抓取任务执行失败，taskId: {}, feedId: {} - {}", taskId, feedId, e.getMessage(), e);
            
            // 存储错误结果
            FetchResult errorResult = FetchResult.builder()
                    .success(false)
                    .errorMessage("抓取任务执行失败: " + e.getMessage())
                    .build();
            taskResults.put(taskId, errorResult);
        }
    }
    
    /**
     * 生成任务ID
     */
    private String generateTaskId() {
        return "fetch_" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);
    }
}

